package com.xuwang.ExceptionHandle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xuwang.Util.TableResult;
import com.xuwang.Util.WriteJson;
import com.xuwang.pojo.User;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Author  460503919
 * @ Date    2021/8/18 12:37
 * @ VERSION 1.0.0
 */
@RestControllerAdvice
public class Exception {
    @ExceptionHandler(NumberFormatException.class)
    public String NumberFormatException(Throwable e) throws JsonProcessingException {
        TableResult<User> tableResult = new TableResult<>(500, "数字格式化异常,请检查是否数字数据中包含其他内容", 0, null);
        String json = null;
        json = WriteJson.getJson(tableResult);
        return json;
    }
    @ExceptionHandler(NullPointerException.class)
    public String NullPointerException(Throwable e) throws JsonProcessingException {
        TableResult<User> tableResult = new TableResult<User>(500, "空指针异常",0, null);
        String json = null;
        json = WriteJson.getJson(tableResult);
        return json;
    }

    @ExceptionHandler(FileNotFoundException.class)
    public Map<String, Object> fileNotFoundException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code", 500);
        stringObjectHashMap.put("msg", Arrays.toString(throwable.getStackTrace()));
        return stringObjectHashMap;
    }

    @ExceptionHandler(ClassNotFoundException.class)
    public Map<String, Object> classNotFoundException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！服务器驱动出错");
        return map;
    }

    @ExceptionHandler(SQLException.class)
    public Map<String, Object> sQLException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！数据库操作失败");
        return map;
    }

    @ExceptionHandler(IOException.class)
    public Map<String, Object> iOException(Throwable throwable) {
        throwable.printStackTrace();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "对不起！文件上传失败");
        return map;
    }
}
